class ConfigEditor {
    constructor() {
        this.currentConfig = null;
        this.currentData = null;
        this.currentSchema = null;
        this.init();
    }

    async init() {
        await this.loadConfigList();
        this.setupEventListeners();
    }

    setupEventListeners() {
        document.getElementById('saveBtn').addEventListener('click', () => this.saveConfig());
        document.getElementById('reloadBtn').addEventListener('click', () => this.reloadCurrentConfig());
    }

    async loadConfigList() {
        try {
            const response = await fetch('/api/configs');
            const configs = await response.json();
            
            const configList = document.getElementById('configList');
            configList.innerHTML = '';
            
            configs.forEach(config => {
                const li = document.createElement('li');
                li.className = 'config-item';
                li.textContent = config.name;
                // 传递不带.json扩展名的文件名
                const filenameWithoutExt = config.filename.replace('.json', '');
                li.onclick = () => this.loadConfig(filenameWithoutExt);
                configList.appendChild(li);
            });
        } catch (error) {
            console.error('加载配置列表失败:', error);
            this.showStatus('加载配置列表失败: ' + error.message, 'error');
        }
    }

    async loadConfig(filename) {
        try {
            this.showLoading(true);
            
            // 加载配置数据和schema
            const [dataResponse, schemaResponse] = await Promise.all([
                fetch(`/api/config/${filename}`),
                fetch(`/api/schema/${filename}`)
            ]);
            
            this.currentData = await dataResponse.json();
            this.currentSchema = await schemaResponse.json();
            this.currentConfig = filename;
            
            // 更新UI状态
            this.updateActiveConfig(filename);
            this.renderForm();
            this.showEditor();
            
        } catch (error) {
            console.error('加载配置失败:', error);
            this.showStatus('加载配置失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }

    updateActiveConfig(filename) {
        // 更新侧边栏选中状态
        document.querySelectorAll('.config-item').forEach(item => {
            item.classList.remove('active');
            // 比较时去掉.json扩展名
            const itemName = item.textContent;
            const compareFilename = filename.replace('.json', '');
            if (itemName === compareFilename) {
                item.classList.add('active');
            }
        });
        
        // 更新标题
        document.getElementById('currentConfig').textContent = this.currentSchema.title || filename;
    }

    renderForm() {
        const formContent = document.getElementById('formContent');
        formContent.innerHTML = '';
        
        if (this.currentSchema.type === 'array') {
            this.renderArrayForm(formContent);
        } else {
            this.renderObjectForm(this.currentData, this.currentSchema, formContent);
        }
    }

    renderArrayForm(container) {
        const arrayContainer = document.createElement('div');
        arrayContainer.className = 'array-container';
        
        this.currentData.forEach((item, index) => {
            const itemContainer = this.createArrayItem(item, index);
            arrayContainer.appendChild(itemContainer);
        });
        
        // 添加新项按钮
        const addButton = document.createElement('button');
        addButton.className = 'btn add-item-btn';
        addButton.textContent = '+ 添加新项';
        addButton.onclick = () => this.addArrayItem();
        
        container.appendChild(arrayContainer);
        container.appendChild(addButton);
    }

    createArrayItem(item, index) {
        const itemContainer = document.createElement('div');
        itemContainer.className = 'array-item';
        
        const header = document.createElement('div');
        header.className = 'array-item-header';
        header.innerHTML = `
            <span>项目 ${index + 1} ${item.id ? `(ID: ${item.id})` : ''}</span>
            <button class="btn btn-danger" onclick="configEditor.removeArrayItem(${index})">删除</button>
        `;
        
        itemContainer.appendChild(header);
        
        if (this.currentSchema.items && this.currentSchema.items.properties) {
            this.renderObjectForm(item, this.currentSchema.items, itemContainer, index);
        }
        
        return itemContainer;
    }

    renderObjectForm(data, schema, container, parentIndex = null) {
        if (!schema.properties) return;
        
        Object.entries(schema.properties).forEach(([key, fieldSchema]) => {
            const formGroup = this.createFormField(key, fieldSchema, data[key], parentIndex, key);
            container.appendChild(formGroup);
        });
    }

    createFormField(key, schema, value, parentIndex, fieldPath) {
        const formGroup = document.createElement('div');
        formGroup.className = 'form-group';
        
        const label = document.createElement('label');
        label.className = 'form-label';
        label.textContent = schema.title || key;
        
        if (schema.description) {
            label.title = schema.description;
            label.textContent += ` (${schema.description})`;
        }
        
        formGroup.appendChild(label);
        
        let input;
        
        switch (schema.type) {
            case 'string':
                if (schema.format === 'textarea') {
                    input = document.createElement('textarea');
                    input.className = 'form-input form-textarea';
                } else {
                    input = document.createElement('input');
                    input.type = 'text';
                    input.className = 'form-input';
                }
                input.value = value || '';
                input.oninput = (e) => this.updateValue(parentIndex, fieldPath, e.target.value);
                break;
                
            case 'number':
            case 'integer':
                input = document.createElement('input');
                input.type = 'number';
                input.className = 'form-input';
                input.value = value || 0;
                if (schema.minimum !== undefined) input.min = schema.minimum;
                if (schema.maximum !== undefined) input.max = schema.maximum;
                input.oninput = (e) => this.updateValue(parentIndex, fieldPath, parseFloat(e.target.value) || 0);
                break;
                
            case 'boolean':
                input = document.createElement('input');
                input.type = 'checkbox';
                input.checked = value || false;
                input.onchange = (e) => this.updateValue(parentIndex, fieldPath, e.target.checked);
                break;
                
            case 'array':
                input = this.createArrayField(key, schema, value, parentIndex, fieldPath);
                break;
                
            case 'object':
                input = this.createObjectField(key, schema, value, parentIndex, fieldPath);
                break;
                
            default:
                input = document.createElement('input');
                input.type = 'text';
                input.className = 'form-input';
                input.value = JSON.stringify(value) || '';
                input.oninput = (e) => {
                    try {
                        const parsed = JSON.parse(e.target.value);
                        this.updateValue(parentIndex, fieldPath, parsed);
                    } catch (err) {
                        this.updateValue(parentIndex, fieldPath, e.target.value);
                    }
                };
        }
        
        formGroup.appendChild(input);
        return formGroup;
    }

    createArrayField(key, schema, value, parentIndex, fieldPath) {
        const container = document.createElement('div');
        container.className = 'array-container';
        
        const items = value || [];
        items.forEach((item, index) => {
            const itemDiv = document.createElement('div');
            itemDiv.className = 'object-container';
            itemDiv.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                    <span class="object-title">${key} 项目 ${index + 1}</span>
                    <button class="btn btn-danger" onclick="configEditor.removeSubArrayItem('${fieldPath}', ${index}, ${parentIndex})">删除</button>
                </div>
            `;
            
            if (schema.items) {
                if (schema.items.type === 'object' && schema.items.properties) {
                    Object.entries(schema.items.properties).forEach(([subKey, subSchema]) => {
                        const subField = this.createFormField(subKey, subSchema, item[subKey], parentIndex, `${fieldPath}.${index}.${subKey}`);
                        itemDiv.appendChild(subField);
                    });
                } else {
                    const input = document.createElement('input');
                    input.className = 'form-input';
                    input.value = typeof item === 'object' ? JSON.stringify(item) : item;
                    input.oninput = (e) => this.updateValue(parentIndex, `${fieldPath}.${index}`, e.target.value);
                    itemDiv.appendChild(input);
                }
            }
            
            container.appendChild(itemDiv);
        });
        
        const addButton = document.createElement('button');
        addButton.className = 'btn btn-primary';
        addButton.textContent = `添加${key}项目`;
        addButton.onclick = () => this.addSubArrayItem(fieldPath, schema.items, parentIndex);
        
        container.appendChild(addButton);
        return container;
    }

    createObjectField(key, schema, value, parentIndex, fieldPath) {
        const container = document.createElement('div');
        container.className = 'object-container';
        
        const title = document.createElement('div');
        title.className = 'object-title';
        title.textContent = schema.title || key;
        container.appendChild(title);
        
        if (schema.properties) {
            Object.entries(schema.properties).forEach(([subKey, subSchema]) => {
                const subField = this.createFormField(subKey, subSchema, value?.[subKey], parentIndex, `${fieldPath}.${subKey}`);
                container.appendChild(subField);
            });
        }
        
        return container;
    }

    updateValue(parentIndex, fieldPath, newValue) {
        if (parentIndex !== null) {
            // 更新数组项中的字段
            const pathParts = fieldPath.split('.');
            let target = this.currentData[parentIndex];
            
            for (let i = 0; i < pathParts.length - 1; i++) {
                const part = pathParts[i];
                if (!isNaN(part)) {
                    target = target[parseInt(part)];
                } else {
                    if (!target[part]) target[part] = {};
                    target = target[part];
                }
            }
            
            const lastKey = pathParts[pathParts.length - 1];
            target[lastKey] = newValue;
        } else {
            // 更新顶级字段
            const pathParts = fieldPath.split('.');
            let target = this.currentData;
            
            for (let i = 0; i < pathParts.length - 1; i++) {
                const part = pathParts[i];
                if (!target[part]) target[part] = {};
                target = target[part];
            }
            
            const lastKey = pathParts[pathParts.length - 1];
            target[lastKey] = newValue;
        }
    }

    addArrayItem() {
        const newItem = this.createDefaultItem();
        this.currentData.push(newItem);
        this.renderForm();
    }

    removeArrayItem(index) {
        if (confirm('确定要删除这个项目吗？')) {
            this.currentData.splice(index, 1);
            this.renderForm();
        }
    }

    addSubArrayItem(fieldPath, itemSchema, parentIndex) {
        const pathParts = fieldPath.split('.');
        let target = parentIndex !== null ? this.currentData[parentIndex] : this.currentData;
        
        for (const part of pathParts) {
            if (!target[part]) target[part] = [];
            target = target[part];
        }
        
        const newItem = itemSchema?.type === 'object' ? {} : '';
        target.push(newItem);
        this.renderForm();
    }

    removeSubArrayItem(fieldPath, itemIndex, parentIndex) {
        if (confirm('确定要删除这个子项吗？')) {
            const pathParts = fieldPath.split('.');
            let target = parentIndex !== null ? this.currentData[parentIndex] : this.currentData;
            
            for (const part of pathParts) {
                target = target[part];
            }
            
            target.splice(itemIndex, 1);
            this.renderForm();
        }
    }

    createDefaultItem() {
        if (!this.currentSchema.items || !this.currentSchema.items.properties) {
            return {};
        }
        
        const defaultItem = {};
        Object.entries(this.currentSchema.items.properties).forEach(([key, schema]) => {
            switch (schema.type) {
                case 'string':
                    defaultItem[key] = '';
                    break;
                case 'number':
                case 'integer':
                    defaultItem[key] = 0;
                    break;
                case 'boolean':
                    defaultItem[key] = false;
                    break;
                case 'array':
                    defaultItem[key] = [];
                    break;
                case 'object':
                    defaultItem[key] = {};
                    break;
                default:
                    defaultItem[key] = null;
            }
        });
        
        return defaultItem;
    }

    async saveConfig() {
        try {
            this.showStatus('保存中...', 'info');
            
            const response = await fetch(`/api/config/${this.currentConfig}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(this.currentData)
            });
            
            const result = await response.json();
            
            if (response.ok) {
                this.showStatus('保存成功！', 'success');
            } else {
                this.showStatus('保存失败: ' + result.error, 'error');
            }
        } catch (error) {
            console.error('保存配置失败:', error);
            this.showStatus('保存失败: ' + error.message, 'error');
        }
    }

    async reloadCurrentConfig() {
        if (this.currentConfig) {
            await this.loadConfig(this.currentConfig);
            this.showStatus('重新加载完成', 'success');
        }
    }

    showEditor() {
        document.getElementById('welcomeScreen').style.display = 'none';
        document.getElementById('editorScreen').style.display = 'flex';
    }

    showLoading(show) {
        // 这里可以添加加载状态显示
    }

    showStatus(message, type) {
        const statusDiv = document.getElementById('statusMessage');
        statusDiv.innerHTML = `<div class="status-message status-${type}">${message}</div>`;
        
        // 3秒后自动隐藏成功消息
        if (type === 'success') {
            setTimeout(() => {
                statusDiv.innerHTML = '';
            }, 3000);
        }
    }
}

// 初始化编辑器
const configEditor = new ConfigEditor();

